package controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import util.Util;
import bean.Customer;
import bean.Model;
import bean.UserType;
import dao.CustomerDAO;
import dao.FundTransactionDAO;
import dao.PositionDAO;
import formBean.CustomerNameForm;


public class ViewCustomerAction extends Action{
	
	private FormBeanFactory<CustomerNameForm> formBeanFactory = FormBeanFactory.getInstance(CustomerNameForm.class);

	private CustomerDAO viewCustomerDAO;
	private FundTransactionDAO transactionDAO;
	private PositionDAO positionDAO;

	public ViewCustomerAction(Model model) {
    	viewCustomerDAO  = model.getCustomerDAO();
    	transactionDAO = model.getFundTransactionDAO();
    	positionDAO = model.getPositionDAO();
	}

	public String getName() { return "viewCustomer.do"; }

    public String perform(HttpServletRequest request) {
        // Set up the errors list
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
        	
        CustomerNameForm form = formBeanFactory.create(request);
		request.setAttribute("form", form);
		if (!form.isPresent()) {
            return "viewCustomerAccount.jsp";
        }
		errors.addAll(form.getValidationErrors());
		if(errors.size()>0)
		{
			return "viewCustomerAccount.jsp";
		}
		
			Customer customer = viewCustomerDAO.getCustomerByUsername(form.getUsername());
			
			if (customer == null) {
				errors.add("No such customer!");
				return "viewCustomerAccount.jsp";
			}
			//viewCustomerDAO.lookupPositions(customer.getId());
			
			//FundTransaction[] transaction = transactionDAO.getTransactionByCustomerId(""+customer.getId());
			Date latestExDate = transactionDAO.getlatestTransaction(customer);
			//List positions = positionDAO.getPositionByCusId("" + customer.getId());
			List positions = viewCustomerDAO.lookupPositions(customer.getId());
			request.setAttribute("positions",positions);			
			
			request.setAttribute("cash", Util.showMoney(customer.getCash()));
			
			if(customer!= null)
			{
				request.setAttribute("customer", customer);
				request.setAttribute("latestExDate", latestExDate);
				return "viewCustomerAccount2.jsp";
			}

		} catch (FormBeanException e) {
			e.printStackTrace();
			return "error.jsp";
		}
        return null;
	}

    @Override
	public UserType getType() {
    	return UserType.Employee;
	}

}
